//app.js
var mta = require('utils/mta_analysis.js');
App({
  onLaunch: function(options) {
    // 登录微信
    // if (!wx.getStorageSync("openId")) {
    // this.loginWechat();
    // }

    // mta.App.init({
    //   "appID": "500614913",
    // });

    mta.App.init({
      "appID": "500614913",
      "eventID": "500663213",
      "statShareApp": true,
      "statReachBottom": true
    });

    // 获取用户信息
    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    //       wx.getUserInfo({
    //         success: res => {
    //           // 可以将 res 发送给后台解码出 unionId
    //           this.globalData.userInfo = res.userInfo

    //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //           // 所以此处加入 callback 以防止这种情况
    //           if (this.userInfoReadyCallback) {
    //             this.userInfoReadyCallback(res)
    //           }
    //         }
    //       })
    //     }
    //   }
    // })

    // wx.setStorageSync("path", options.path);
    // if (options.path.indexOf("pages/app") >= 0) {
    // var url = this.globalData.host + '/lx/mini/user/info';
    // var params = {};
    // var success = res => {
    //   this.globalData.userInfo = res.info

    //   if (this.userInfoReadyCallback) {
    //     this.userInfoReadyCallback(res)
    //   }
    // }
    // var fail = res => {
    //   if (res != null && res.status == 401) {
    //     wx.reLaunch({
    //       url: '/pages/app/user/login/login'
    //     })
    //   }
    // };
    // var complete = function() {};
    // this.globalData.utils.request(url, params, success, fail, complete);
    // }
    // CryptoJS.enc.Base64.stringify('str');
    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.globalData.navHeight = res.statusBarHeight + 46;
      }, fail(err) {
        console.log(err);
      }
    })
    this.serverLogin({
      success() {
        console.log('自动登录成功')
      },
      fail() {
        console.log('自动登录失败')
      }
    })
  },
  globalData: {
    userInfo: null,
    openId: null,
    unionId: null,
    token: null,
    utils: require('utils/util'),
    cryptoJS: require('utils/crypto-js'),
    aesKey: 'liuxue!@#$%^&*()',
    themeColor: '#e0342e', // 红
    themeColor2: '#ea981b', // 橙
    themeColor3: '#0076ff', // 蓝
    defaultColor: '#929292',
    borderColor: '#f5f5f5',
    navHeight: null,
    host: 'https://release.zhen-yee.com',
    // host: 'http://release.zhen-yee.com',
    // host: 'http://192.168.50.18:9090',
    // majors: [
    //   "Arts & Humanities　艺术类",
    //   "Education　教育类",
    //   "Law　法律类",
    //   "Psychology　心理学类",
    //   "Business & Economics　商业与经济类",
    //   "Clinical, Pre-clinical & Health　医学健康类",
    //   "Computer Science　计算机科学类",
    //   "Engineering & Technology　工程与科学类",
    //   "Life Sciences　生命科学类",
    //   "Natural Science　自然科学类",
    //   "Social Sciences　社会科学类"
    // ]
    majors: [
      "Arts & Humanities 艺术人文",
      "Education 教育",
      "Law 法律",
      "Psychology 心理学",
      "Business 商业",
      "Clinical 临床医学",
      "Computer Science 计算机科学",
      "Engineering 工程",
      "Life Sciences 生命科学",
      "Natural Science 自然科学",
      "Social Sciences 社会科学"
    ],
    lastQuestions: [],
    lastAnswers: [],
    lastWrongList: []
  },
  login(referrer, isFromUser) {
    if (!wx.getStorageSync("user")) {
      if (isFromUser) {
        wx.switchTab({
          url: '/pages/app/schools/index/index'
        })
      }
      wx.setStorageSync("path", referrer);
      // wx.reLaunch({
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/app/user/login/login'
        })
      }, 200);
    } else {
      var url = this.globalData.host + '/lx/mini/user/info';
      var params = {};
      var success = res => {
        this.globalData.userInfo = res.info
        wx.setStorageSync("user", res.info)

        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res);
        }
      }
      var fail = res => {
        if (res != null && res.status == 401) {
          wx.setStorageSync("user", null);
          if (isFromUser) {
            wx.switchTab({
              url: '/pages/app/schools/index/index'
            })
          }
          wx.setStorageSync("path", referrer);
          // wx.reLaunch({
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/app/user/login/login'
            })
          }, 200);
        }
      };
      var complete = function() {};
      this.globalData.utils.request(url, params, success, fail, complete);
    }
  },
  loginWechat(callback) {
    wx.login({
      success: res => {
        var code = res.code;

        wx.request({
          url: this.globalData.host + '/lx/mini/user/wechatLogin',
          data: {
            code: code
          },
          success: res => {
            wx.setStorageSync("openId", res.data.info);
            if (callback) {
              callback();
            }
          }
        })
      }
    })
  },
  serverLogin(param) {
    var that = this;
    if (that.globalData.openId) {
      console.log('已登录')
      return
    }
    wx.login({
      success: function(res) {
        var code = res.code
        wx.getUserInfo({
          success: function(res) {
            var userInfo = res.userInfo
            var nickName = userInfo.nickName
            var avatarUrl = userInfo.avatarUrl
            var gender = userInfo.gender //性别 0：未知、1：男、2：女
            var province = userInfo.province
            var city = userInfo.city
            var country = userInfo.country


            var host = that.globalData.host
            that.request({
              url: host + '/lx/mini/user/auth',
              data: {
                code: code,
                nickName: nickName,
                avatarUrl: avatarUrl,
                gender: gender,
                province: province,
                country: country
              },
              success: function(res) {
                if (res.data.status != 200) {
                  param.fail()
                  return
                }
                var openId = res.data.info.openId
                var unionId = res.data.info.unionId
                var token = res.data.info.token
                that.globalData.openId = openId
                that.globalData.unionId = unionId
                that.globalData.token = token
                wx.setStorage({
                  key: "openId",
                  data: openId
                })
                wx.setStorage({
                  key: "token",
                  data: token
                })
                // typeof cb == "function" && cb(that.globalData.userInfo)
                param.success()
              }
            })
          }
        })
      },
      fail(errMsg) {
        console.log(errMsg)
        param.fail()
      }
    })
  },
  request: function(param) {
    var token = this.globalData.token
    var appid = this.globalData.appid
    var version = this.globalData.version
    var openId = this.globalData.openId
    if (param.data == null) {
      param.data = {
        token: token,
        appid: appid,
        version: version,
        openId: openId
      }
    } else {
      param.data['token'] = token
      param.data['appid'] = appid
      param.data['version'] = version
      param.data['openId'] = openId
    }
    return wx.request(param)
  },
  
  /**
   * 设置监听器
   */
  setWatcher(data, watch) { // 接收index.js传过来的data对象和watch对象
    Object.keys(watch).forEach(v => { // 将watch对象内的key遍历
      this.observe(data, v, watch[v]); // 监听data内的v属性，传入watch内对应函数以调用
    })
  },

  /**
   * 监听属性 并执行监听函数
   */
  observe(obj, key, watchFun) {
    var val = obj[key]; // 给该属性设默认值
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function(value) {
        val = value;
        watchFun(value, val); // 赋值(set)时，调用对应函数
      },
      get: function() {
        return val;
      }
    })
  }
})